﻿using Newtonsoft.Json.Linq;
using O2S.Components.PDFRender4NET;
using System;
using System.Configuration;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using utils;

namespace view
{
    public partial class PrinterConfig : UserControl
    {

        private String currentPrinter;
        public String license;

        public PrinterConfig()
        {
            InitializeComponent();
            this.InitPrinterList();
        }



        private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void PrinterConfig_Load(object sender, EventArgs e)
        {
            Thread thread = new Thread(() =>
            {
                _ = this.InitWebSocketAsync();
            });
            thread.Start();
        }

        private async Task InitWebSocketAsync()
        {
            ClientWebSocket webSocket = new ClientWebSocket();

            String webSocketUrl = ConfigurationManager.AppSettings.Get("webSocket");

            Uri uri = new Uri(webSocketUrl + this.license);


            var cts = new CancellationTokenSource();
            await webSocket.ConnectAsync(uri, cts.Token);

            Console.WriteLine(webSocket.State);

            Task<Task> task = Task.Factory.StartNew(
                async () =>
                {
                    var rcvBytes = new byte[8192];
                    var rcvBuffer = new ArraySegment<byte>(rcvBytes);
                    while (true)
                    {
                        WebSocketReceiveResult rcvResult = await webSocket.ReceiveAsync(rcvBuffer, cts.Token);
                        byte[] msgBytes = rcvBuffer.Skip(rcvBuffer.Offset).Take(rcvResult.Count).ToArray();
                        string rcvMsg = Encoding.UTF8.GetString(msgBytes);
                        Console.WriteLine("Received: {0}, CurrentPrinter: {1}", rcvMsg, this.currentPrinter);


                        JObject jo = JObject.Parse(rcvMsg);
                        var token = jo["token"];
                        var printTemplateId = jo["printTemplateId"];
                        var paramsStr = jo["params"];
                        bool isMdmPrint = Convert.ToBoolean(jo["isMdmPrint"]);
                        Console.WriteLine("params: {0}", paramsStr);

                        Print(token.ToString(), printTemplateId.ToString(), paramsStr.ToString(), isMdmPrint);
                    }
                }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            while (true) ;
        }

        private void ListView1_SelectedIndexChanged_1(object sender, EventArgs e)
        {

        }

        private void Button1_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择打印机");
                return;
            }

            this.currentPrinter = this.listView1.SelectedItems[0].Text;
        }


        private void InitPrinterList()
        {
            ImageList imageList = new ImageList();
            imageList.ImageSize = new Size(1, 40);
            this.listView1.SmallImageList = imageList;

            this.listView1.BeginUpdate();
            foreach (String sPrinter in PrinterSettings.InstalledPrinters)
            {
                Console.WriteLine(sPrinter);
                _ = this.listView1.Items.Add(sPrinter);
            }
            this.listView1.EndUpdate();
        }

        private int Print(String token, String printTemplateId, String paramStr, bool isMdmPrint)
        {
            if (String.IsNullOrEmpty(this.currentPrinter))
            {
                return -1;
            }

            Stream myResponseStream;


            myResponseStream = HttpUtils.ExportPdf(token, printTemplateId, paramStr, isMdmPrint);


            var ms = StreamToMemoryStream(myResponseStream);


            int isOK = 0;
            //PDFFile file = PDFFile.Open(ms);
            PDFFile file = PDFFile.Open(ms);

            PrinterSettings settings = new PrinterSettings();
            PrintDocument pd = new PrintDocument();
            settings.PrinterName = this.currentPrinter;
            settings.PrintToFile = false;

            //设置纸张大小（可以不设置，取默认设置）3.90 in,  8.65 in
            //PaperSize ps = new PaperSize("test", 4, 9);
            //ps.RawKind = 9; //如果是自定义纸张，就要大于118，（A4值为9，详细纸张类型与值的对照请看http://msdn.microsoft.com/zh-tw/library/system.drawing.printing.papersize.rawkind(v=vs.85).aspx）
            O2S.Components.PDFRender4NET.Printing.PDFPrintSettings pdfPrintSettings = new O2S.Components.PDFRender4NET.Printing.PDFPrintSettings(settings)
            {
                //pdfPrintSettings.PaperSize = ps;
                PageScaling = O2S.Components.PDFRender4NET.Printing.PageScaling.FitToPrinterMarginsProportional
            };
            pdfPrintSettings.PrinterSettings.Copies = 1;

            try
            {
                file.Print(pdfPrintSettings);
                isOK = 1;
            }
            catch (Exception)
            {
                isOK = -1;
                throw;
            }
            finally
            {

                file.Dispose();
            }
            return isOK;
            //return 1;

        }

        MemoryStream StreamToMemoryStream(Stream instream)
        {
            MemoryStream outstream = new MemoryStream();
            const int bufferLen = 4096;
            byte[] buffer = new byte[bufferLen];
            int count = 0;
            while ((count = instream.Read(buffer, 0, bufferLen)) > 0)
            {
                outstream.Write(buffer, 0, count);
            }
            return outstream;
        }
    }
}
